package com.study.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author Qi XueSong
 */
@Component("collectionUtils")
public class CollectionUtils {

    @Autowired
    private DruidDataSource dataSource;
    //存储当前线程的连接
    private final ThreadLocal<DruidPooledConnection> threadLocal = new ThreadLocal<>();

    /**
     * 获取连接
     */
    public DruidPooledConnection getConnection() throws SQLException {
        // 获取当前线程中的连接
        DruidPooledConnection druidPooledConnection = threadLocal.get();
        //判断当前线程中是否存在连接
        if(druidPooledConnection == null){
            //不存在，则从工具类中获取连接
            druidPooledConnection = dataSource.getConnection();
            //将连接放到当前线程中
            threadLocal.set(druidPooledConnection);
        }
        return druidPooledConnection;
    }
}
